package es.ats.codington.festival.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import es.ats.codington.festival.domain.Visitor;
import es.ats.codington.festival.services.VisitorService;

public class PresentUpdatePasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/updatePassword.jsp");
        requestDispatcher.forward(request, response);
		
        
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession sesion = request.getSession(false);
		if (sesion == null){
			RequestDispatcher requestDispatcher = request.getRequestDispatcher("/");
	        requestDispatcher.forward(request, response);
		}
		else{
		
			Visitor visitor = new Visitor();
			VisitorService vs = new VisitorService();
			try {
			
				
				String password = request.getParameter("password");
				int peopleId = (Integer) sesion.getAttribute("peopleid");
	
				visitor.setPeopleId(peopleId);
				visitor.setPassword(password);
							
				int a=vs.changePassword(visitor);
				if(a==0 )
				{
					request.setAttribute("error", "Your passwords do not match. Please try again");
					response.sendRedirect("jsp/error.jsp");			
				
				}
				
				else
				{
					
					
						RequestDispatcher requestDispatcher = request.getRequestDispatcher("jsp/home.jsp");
				        requestDispatcher.forward(request, response);
					
					
				}


			
			} 	
			catch (Exception e) {
				request.setAttribute("error", "Something were wrong with the change of password. Please, try it again in a few minutes.");
				response.sendRedirect("jsp/error.jsp");			
			}
		}
	}
}
